<?php
namespace Common\Controller;
use Think\Controller;

// 后台基控制器
class AdminBaseController extends Controller {

    protected  $rule;

    /**
     * 构造函数
     */
    public function _initialize(){
        $uid = is_login();
        if(!$uid) $this->redirect('Public/login');
        define('UID',$uid);

        // 判断超级管理员
        $adminSuper = (UID == C('ADMIN_SUPER')) ? true : false ;
        define('SUPER',$adminSuper);

        $this->rule = MODULE_NAME.'/'.CONTROLLER_NAME.'/'.ACTION_NAME;
        $this->assign('rule',$this->rule);

        // 检测节点控制权限
        if(!SUPER){
            $Auth = new \Think\Auth();
            if( !$Auth->check($this->rule,UID) ){
                $this->error('未授权访问!');
            }
        }

        $this->initMenu(); // 系统后台菜单
    }

    // 后台系统菜单
    private function initMenu(){
        session('admin_menu',null);
        if(!session('?admin_menu')){
            $menu = $this->getAuthRule();
            if(!SUPER){
                $Auth = new \Think\Auth();
                foreach ($menu as $k =>$v) {
                    if( !$Auth->check($v['name'],UID,array('in','2,3')) ){
                        unset($menu[$k]);
                    }
                }
                unset($_SESSION['_AUTH_LIST_'.UID.'2,3']);
            }

            // 选中
            foreach($menu as $k=>&$v){
                if($this->rule == $v['name']){
                    $this->assign('activeId',$v['pid']);
                }
            }
            $admin_menu = self::getTree($menu,0);
            session('admin_menu',$admin_menu);
        }
    }


    //缓存后台所有菜单
    private function getAuthRule(){
        $auth_rule = F('AdminAuth');
        if(!$auth_rule){
            $auth_rule = M('AuthRule')->field('id,pid,name,title,icon')->where('type IN (2,3) AND status = 1')->order('sort ASC,id ASC')->select();
            F('AdminAuth',$auth_rule);
        }
        return $auth_rule;
    }


    // 递归生成无限级后台菜单
    private static function getTree($arr,$pid){
        $result = array();
        foreach ($arr as $v) {
            if($v['pid'] == $pid){
                $r['id'] = $v['id'];
                $r['url'] = $v['name'];
                $r['name'] = $v['title'];
                $r['icon'] = $v['icon']?$v['icon']:'link';

                $r['item'] = self::getTree($arr,$v['id']);
                if(empty($r['item'])) unset($r['item']);
                $result[]=$r;
            }
        }
        return $result;
    }




    /**
     * 检测是否登录
     * @return bool|int 成功登录,返回uid，否则返回false
     */
    private function isLogin(){
        if($admin = session('adminInfo')){
            $uid = $admin['id'];
        }elseif($token = cookie('adminToken')){
            $uid = D('Admin')->adminToken('check');
        }else{
            return false;
        }
        return intval($uid);
    }




}